<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule\ModulesModule;


use Nette\Environment;
use Albireo\Forms\AlbireoForm;
use Nette\Forms\Form;
use Nette\Collections\ArrayList;
use KernelModule\BasePresenter;
use Celebrio\Core\ServiceProvider;
use Celebrio\Core\Config;

/**
 * Kernel modules management presenter.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class ConsolePresenter extends BasePresenter {

    private $configManagement;

    /**
     * startup is always called
     */
    public function startup() {
        parent::startup();
        $this->configManagement = null; //new Config::current();
        $this->showMenu();
    }


    public function actionDefault() {
        if ($this->configManagement->getActive("database") == null) {
            $this->flashMessage(_('No database module is set active.'));
            $this->redirect('ModulesManagement:default');
        }
        $namespace = $this->getSession("console");
        if (isset($namespace->queries)) {
            $this->template->queries = $namespace->queries;
        }
        $this->template->database = $this->configManagement->getActive("database");
    }

    public function renderDefault() {
        $this->template->title = $this->configManagement->getActive("database")." "._("Console");
        $this->template->form = $this['console'];
    }

    protected function createComponentConsole() {
        $form = new AlbireoForm();
        $form->addTextArea("albireoConsole", $this->configManagement->getActive("database").">", NULL, 1);
        $form->addSubmit('process', _('Process'));
        $form->onSubmit[] = callback($this, 'processQuery');
        return $form;
    }

    public function processQuery($form) {
        $values = $form->values;
        $this->callConsole($values['albireoConsole']);
    }

    private function callConsole($query) {
        $namespace = $this->getSession("console");
        if (isset($namespace->queries)) {
            $namespace->queries[] = $query;
        } else {
            $namespace->queries = array($query);
        }
        $this->template->queries = $namespace->queries;
        $this->template->console = ServiceProvider::getService("Celebrio-Database-IDatabase")->console($query);
    }

    public function handleProcess($query) {
        $query = htmlspecialchars($query);
        $this->invalidateControl("console");
        $this->invalidateControl("list"); // should this be here?
        $this->callConsole($query);
    }
}